function calculate(str) {
const regex = /([+\-*/])/;
const arr = str.split(regex).map(item => item.trim());

if (arr.length !== 3 || !['+', '-', '*', '/'].includes(arr[1])) {
  return 'Invalid input';
}

const num1 = Number(arr[0]);
const num2 = Number(arr[2]);
const operator = arr[1];

switch(operator) {
  case '+':
    return num1 + num2;
  case '-':
    return num1 - num2;
  case '*':
    return num1 * num2;
  case '/':
    if (num2 === 0) {
      return 'Cannot divide by zero';
    }
    return num1 / num2;
  default:
    return 'Invalid input';
}
}

// 测试
console.log(calculate('1 + 2')); // 3
console.log(calculate('3-2')); // 1
console.log(calculate('2 * 3')); // 6
console.log(calculate('4 / 2')); // 2

console.log(calculate('1 + x')); // Invalid input
console.log(calculate('1 2 3')); // Invalid input
console.log(calculate('4 / 0')); // Cannot divide by zero